import service from '@/api/service';
export default {
  namespaced: true,
  state: {
    queryObject: {
      pageIndex: 1,
      pageSize: 20,
      sortFields: {
        UpdateTime: false
      },
      parameters: {
        keyword: ""
      }
    },
    dataTable: {
      result: [],
      pageIndex: 1,
      pageSize: 20,
      pageCount: 0,
      rowCount: 0,
    },
    currentItem: {
    }
  },
  mutations: {
    setData(state, data) {
      state.dataTable = data
    },
    setParameters(state, parameters) {
      for (let name in parameters) {
        state.queryObject.parameters[name] = parameters[name];
      }
    }
  },
  actions: {
    query({ commit, state }) {
      return service.template
        .query({ data: state.queryObject })
        .then(response => {
          commit('setData', response.success ? response.data : null);
          return response;
        })
        .catch(error => {
          return error;
        });
    },
    item({ commit }, name) {
      return service.template
        .item({ params: {name} })
        .then(response => {
          return response;
        })
        .catch(error => {
          return error;
        });
    },
    create({ commit, state, dispatch }, dto) {
      return service.template
        .create({ data: dto })
        .then((response) => {
          if (response.success) dispatch("query");
          return response;
        })
        .catch((error) => {
          return error;
        });
    },
    update({ commit, state, dispatch }, dto) {
      return service.template
        .update({ data: dto })
        .then((response) => {
          if (response.success) dispatch("query");
          return response;
        })
        .catch((error) => {
          return error;
        });
    },
    delete({ commit, state, dispatch }, name){
      return service.template
        .delete({data:name}).then(response => {
          if (response.success) dispatch('query');
          return response;
        }).catch(error => {
            return error;
        });
    }
  }
}
